import React from 'react'
import MyHead from '../../components/MyHead'
import{
  Form,
  Button,
  Input,
} from 'antd-mobile'
import PassInput from '../../components/PassInput'
import { reg } from '../../utils/validate'
import { useCommonFunc } from '../../hooks/useCommon'
import { useLocalData } from '../../hooks/useLocalData';
import { useDispatch } from 'react-redux'
import { ChangePassAPI } from '../../api/api'
import { ShowMessage } from '../../utils/message'
import { changeUserInfo } from '../../rtk/reducers/infoSilce'

interface PassTypes{
  oldPassword:string,
  newPassword:string,
  dbnewpass?:string,
}

const ChangePass = () => {
  const [form] = Form.useForm()
  const { gotopage } = useCommonFunc()
  const { setToken } = useLocalData()
  const dispatch = useDispatch()

  // 确认修改密码
  const submitForm = () => {
    console.log("form",form);
    form.validateFields()  // 表单校验
    .then(async(value:PassTypes)=>{
      let res:any = await ChangePassAPI({
        oldPassword:value.oldPassword,
        newPassword:value.newPassword
      })
      if(res.code == "200"){
        ShowMessage(res.msg)
        gotopage('/login')
        // 注销旧账号
        setToken('')
        dispatch(changeUserInfo(null))
      }
    })
    .catch(err=>{
      ShowMessage("表单验证失败")
    })
  }

  return (
    <div>
      <MyHead title='修改密码' />
      <Form
        form={form}
        layout='vertical'
        initialValues={{ }}
        footer={
          <div
            style={{ display: 'flex' }}
          >
            <Button style={{ flex: 1, margin: "8px" }} color='danger' size='middle' onClick={submitForm}>
                确认修改
            </Button>
          </div>
        }
      >
        <Form.Header>修改密码</Form.Header>

        <PassInput
          name='oldPassword'
          label='旧密码'
          placeholder='请输入旧密码'
        ></PassInput>

        <PassInput
          name='newPassword'
          label='新密码'
          placeholder='请输入旧密码'
        ></PassInput>

        <PassInput
          name='dbPassword'
          label='确认密码'
          placeholder='请输入确认密码'
          rules={[
            {
              validator:(_:any,value:any)=>{
                if(reg.pwd.test(value)){
                  if(form.getFieldValue('newPassword')===value){
                    return Promise.resolve()
                  }else{
                    return Promise.reject(new Error('两次密码不相同'))
                  }
                }else{
                  return Promise.resolve()
                }
              }
            }
          ]}
        ></PassInput>

      </Form>
    </div>
  )
}

export default ChangePass